from doctest import debug
from fastapi import FastAPI, HTTPException
import uvicorn
import asyncio
from datetime import datetime

from pydantic import BaseModel
from typing import Optional
import logging
import threading
import task_init
from apscheduler.schedulers.background import BackgroundScheduler
from typing import Dict, Any
from flask import jsonify


scheduler = BackgroundScheduler()


app = FastAPI()  # ← 变量名必须是 my_app！

# 全局引用（需在主程序中注入）
global_strategy_pool = {}
global_account_id = None
global_subscribe_func = None

@app.get('/health')
def health():
    return jsonify({"status": "ok", "instance_count": len(global_strategy_pool)})


class AddStrategyRequest(BaseModel):
    name: str
    code: str

@app.post("/add_strategy")
def add_strategy(data: Dict[str, Any]):
    """
    添加新股票策略实例
    POST /add_strategy
    {
        "stock_code": "600519.SH",
        "params": {
            "ma_window": 20,
            "vol_multiplier": 1.5,
            "order_volume": 100,
            "cool_down": 5
        }
    }
    """
    stock_code = data.get("stock_code")
    params = data.get("params", {})

    if not stock_code:
        return  {"code": 400,"msg": "stock_code is required"}

    if stock_code in global_strategy_pool:
        return {"code": 409,"msg": f"{stock_code} already exists"}

    from strategy_instance import StrategyInstance
    instance = StrategyInstance(stock_code, params)
    global_strategy_pool[stock_code] = instance

    # 增量订阅行情（关键！）
    if global_subscribe_func:
        global_subscribe_func([stock_code])


# 直接返回 dict
    return {
        "code": 200,
        "msg": "OK",
        "result": {
            "strategy_id": {stock_code},
            "data": instance.to_dict()
        }
    }

@app.route('/remove_strategy/<stock_code>', methods=['DELETE'])
def remove_strategy(stock_code):
    """删除策略实例"""
    if stock_code in global_strategy_pool:
        del global_strategy_pool[stock_code]
        return jsonify({"message": f"{stock_code} removed"})
    return jsonify({"error": "stock_code not found"}), 404

@app.route('/update_params', methods=['POST'])
def update_params():
    """
    更新参数
    POST /update_params
    {
        "stock_code": "600519.SH",
        "params": {"ma_window": 25}
    }
    """
    data = request.json
    stock_code = data.get("stock_code")
    new_params = data.get("params", {})

    if stock_code not in global_strategy_pool:
        return jsonify({"error": "stock_code not found"}), 404

    global_strategy_pool[stock_code].update_params(new_params)
    return jsonify({"message": "params updated"})

@app.route('/list_strategies', methods=['GET'])
def list_strategies():
    """列出所有策略实例状态"""
    return jsonify({
        code: inst.to_dict()
        for code, inst in global_strategy_pool.items()
    })

def start_flask_server(port=5000):
    """在子线程启动 Flask"""
    app.run(host='0.0.0.0', port=port, debug=False, use_reloader=False)

# 注入全局依赖（由主程序调用）
def init_flask_api(strategy_pool, account_id, subscribe_func):
    global global_strategy_pool, global_account_id, global_subscribe_func
    global_strategy_pool = strategy_pool
    global_account_id = account_id
    global_subscribe_func = subscribe_func




class TaskRequest(BaseModel):
    """任务请求模型"""
    param1: Optional[str] = None
    param2: Optional[int] = None
    data: Optional[dict] = None



# 启动后台任务
def start_background_task():
    # BackgroundScheduler.start() 是非阻塞的！
    scheduler.add_job(task_init.init_task_zb(), 'interval', seconds=10)
    scheduler.start()  # ✅ 安全


@app.on_event("startup")
async def startup_event():
    print(">>> STARTUP BEGIN")
    # BackgroundScheduler.start() 是非阻塞的！
    scheduler.add_job(task_init.init_task_zb, trigger='date')
    scheduler.start()  # ✅ 安全
    # ... your code ...
    print(">>> STARTUP END")


# 使用示例
# if __name__ == "__main__":
#     # import uvicorn
#     print(f'系统main方法初始化启动')
    # start_background_task()
    # service = FastAPIService(host='0.0.0.0', port=9088)
    # print(f'系统main方法初始化启动完成,进入挂机中')
    # service.run()

    # uvicorn.run(app, host="0.0.0.0", port=9012)
